<template>
  <!-- 分支1：axios 触发下载进度时，显示全局遮罩的圆形进度条 -->
  <div v-if="isGlobalDownloadProgress" class="global-progress-mask">
    <div class="progress-container">
      <el-progress type="circle" :percentage="downloadPercent" :stroke-width="6" :size="80" :status="progressStatus" />
      <p class="progress-text">{{ progressDesc }}</p>
    </div>
  </div>

  <!-- 分支2：原有逻辑不变，目标元素定位的 Loading（非下载场景用） -->
  <div v-else-if="visible" class="loading-mask" :style="maskStyle">
    <div class="loading-spinner" :style="{ '--scale-factor': clampedScaleFactor }">
      <div class="spinner-icon"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import event from '../eventCenter/index'

// ———— 原有 Loading 逻辑：100% 保留，未做任何修改 ————
let resizeObserver = null
const visible = ref(false)
const targetElement = ref(null)
const rect = ref({})
const borderRadius = ref('0')

const clampedScaleFactor = computed(() => {
  const scaleFactor = Math.min(Math.min(rect.value.width / 60, rect.value.height / 60), 2)
  return scaleFactor.toFixed(2)
})

const maskStyle = computed(() => {
  if (!targetElement.value) return {}
  const computedStyle = window.getComputedStyle(targetElement.value)
  const borderTopWidth = parseFloat(computedStyle.borderTopWidth) || 0
  const borderRightWidth = parseFloat(computedStyle.borderRightWidth) || 0
  const borderBottomWidth = parseFloat(computedStyle.borderBottomWidth) || 0
  const borderLeftWidth = parseFloat(computedStyle.borderLeftWidth) || 0
  const targetBorderRadius = computedStyle.borderRadius || '0'
  borderRadius.value = targetBorderRadius

  return {
    position: 'absolute',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    margin: 0,
    top: `${-borderTopWidth}px`,
    right: `${-borderRightWidth}px`,
    bottom: `${-borderBottomWidth}px`,
    left: `${-borderLeftWidth}px`,
    transition: 'opacity .3s',
    width: `${rect.value.width + borderLeftWidth + borderRightWidth}px`,
    height: `${rect.value.height + borderTopWidth + borderBottomWidth}px`,
    zIndex: 9999,
    borderRadius: targetBorderRadius
  }
})

const show = el => {
  targetElement.value = el.$el || el
  resizeObserver = new ResizeObserver(() => {
    rect.value = targetElement.value.getBoundingClientRect()
  })
  resizeObserver.observe(targetElement.value)
  rect.value = targetElement.value.getBoundingClientRect()
  visible.value = true
}

const hide = () => {
  visible.value = false
  targetElement.value = null
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
}
// ———— 原有逻辑结束 ————

// ———— 新增：axios 下载进度专用逻辑（不影响原有逻辑） ————
const downloadPercent = ref(0) // 存储axios传来的进度值
const isGlobalDownloadProgress = ref(false) // 全局进度条显示开关（仅axios触发）

// 进度条状态（Element Plus 自带）
const progressStatus = computed(() => {
  return downloadPercent.value === 100 ? 'success' : 'active'
})

// 进度描述文本
const progressDesc = computed(() => {
  return downloadPercent.value === 100 ? '下载完成，即将关闭...' : `正在下载：${downloadPercent.value}%`
})

// 监听axios触发的下载进度事件
onMounted(() => {
  // 对接你封装的customAxios中抛出的"downloadProgress"事件
  event.on('downloadProgress', progressData => {
    // 1. 更新进度值（确保在0-100范围）
    downloadPercent.value = Math.max(0, Math.min(100, progressData.percent))
    // 2. 开启全局进度条（覆盖原有目标元素Loading的显示逻辑）
    isGlobalDownloadProgress.value = true
    // 3. 下载完成后自动关闭，并重置状态
    if (downloadPercent.value === 100) {
      setTimeout(() => {
        isGlobalDownloadProgress.value = false
        downloadPercent.value = 0
      }, 800)
    }
  })

  // 可选：监听下载失败事件，关闭进度条
  event.on('downloadError', () => {
    isGlobalDownloadProgress.value = false
    downloadPercent.value = 0
  })
})

// 组件卸载时移除事件监听，避免内存泄漏
onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
  event.off('downloadProgress')
  event.off('downloadError')
})

// 暴露原有方法，新增下载失败时的关闭方法（可选）
defineExpose({
  show, // 原有方法：目标元素定位的Loading
  hide, // 原有方法：关闭目标元素Loading
  hideDownloadProgress: () => {
    // 新增：手动关闭全局下载进度条
    isGlobalDownloadProgress.value = false
    downloadPercent.value = 0
  }
})
</script>

<!-- 原有样式保留，新增全局进度条样式 -->
<style>
.loading-parent {
  position: relative !important;
  pointer-events: none;
  user-select: none;
}
/* 新增：全局进度条遮罩样式 */
.global-progress-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(2px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.progress-container {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}
.progress-text {
  font-size: 14px;
  color: #606266;
  margin: 0;
}
</style>

<style scoped>
.loading-mask {
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none;
}

.loading-spinner {
  transform: scale(var(--scale-factor, 1));
  color: black;
  font-size: 12px;
}

.spinner-icon {
  width: 32px;
  height: 32px;
  border: 2px solid;
  border-radius: 50%;
  border-color: #3498db transparent transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>